package com.liujiajin;

import java.io.File;
import java.net.URL;

import com.mylib.Myclass;

/**
 * 测试使用同一个类加载器加载不同jar包的两个同名类
 */
public class ClassLoadDemo1 {
    public static void main(String[] args) throws Exception {
        // 创建一个自定义类加载器
    	File libPath = new File(Constants.LIB);

    	String repository = (new URL("file", null, libPath.getCanonicalPath() + File.separator)).toString();
    	URL[] urls = {new URL(repository + "mylib-1.0.jar"), new URL(repository + "mylib-2.0.jar")};
    	CustomClassLoader classLoader = new CustomClassLoader(urls);
        // 加载两个版本的 MyClass
        Class<?> myClass1 = classLoader.loadClass("com.mylib.Myclass");
        Class<?> myClass2 = classLoader.loadClass("com.mylib.Myclass");

        // 创建两个版本的 MyClass 实例
        Object instance1 = myClass1.getDeclaredConstructor().newInstance();
        Object instance2 = myClass2.getDeclaredConstructor().newInstance();

        // 调用方法
        myClass1.getMethod("printVersion").invoke(instance1);
        myClass2.getMethod("printVersion").invoke(instance2);

        // 演示类冲突
        System.out.println("instance1 instanceof MyClass: " + (instance1 instanceof Myclass));
        System.out.println("instance2 instanceof MyClass: " + (instance2 instanceof Myclass));
        System.out.println("myClass1 == myClass2: " + (myClass1 == myClass2));
    }
}
